<?php
class admintemp {//模板类

	/**
	 * 引用模板
	 * $c 为模板路径 
	 * $post 页面数据
	 */
	function _temp($c,$post=array()){
		extract($post);
		$temp = V_DIR.$c; //模板文件路径
		$path = str_replace("/",DS,$temp);  //转换路径
	    $mob = explode(DS.'v'.DS, $path);
		$mb = explode(DS, $mob[count($mob)-1]);   //判断是admin还是html
		$wjlj = $path.'.html';    //模板完整路径
		$ca = V_DIR.'admin'.DS.'cache';    //缓存文件目录
		$dirs = file_exists($ca);//查看缓存目录是否存在
		if(empty($dirs)){//如果缓存目录不存在
			mkdir($ca,0777);//创建缓存目录
		}
		$cach = $ca.DS.implode('_',$mb).'_'.md5($path).'_cache.php';  //缓存文件路径
		if(file_exists($wjlj)){   //查看是否存在模板文件
			if(file_exists($cach)){
				if(filemtime($wjlj)>filemtime($cach)){       //模板文件修改时间大于缓存文件修改时间
					self::jxtemp($wjlj,$cach);  //解析模板
				}
			}else{
				self::jxtemp($wjlj,$cach);  //解析模板
			}
			include $cach;
		}
	}
	
	/**
	 * 解析模板
	 * $temp  模板路径
	 * $cach  模板缓存路径
	 */
	function jxtemp($temp,$cach){
		$neirong = @file_get_contents($temp);  //获取模板中的内容
		$neirong = preg_replace('/\{(\$[a-zA-Z_\x7f-\xff][\w\x7f-\xff\[\'\$\]\.]*)\}/', '<?php echo \\1; ?>',$neirong);
		$neirong = preg_replace('/\{code\(([^\{\}]+)\)\}/','<? \\1; ?>',$neirong);
		$neirong = preg_replace('/\{prt\(([^\{\}]*)\)\}/','<?php print_r(\\1); ?>',$neirong);
		$neirong = preg_replace('/\{include\(([^\{\}]+)\)\}/','<? include \\1; ?>',$neirong);
		$neirong = preg_replace('/\{while\(([^\{\}]+)\)\}/','<? while (\\1) { ?>',$neirong);
		$neirong = preg_replace('/\{if\(([^\{\}]+)\)\}/','<? if (\\1){ ?>',$neirong);
		$neirong = preg_replace('/\{elseif\(([^\{\}]+)\)\}/','<? } elseif(\\1) { ?>',$neirong);
		$neirong = preg_replace('/\{else}/','<? }else{ ?>',$neirong);     //eg :else
		$neirong = preg_replace('/\{for\(([^\{\}]+)\)\}/','<? for (\\1) { ?>',$neirong);
		$neirong = preg_replace('/\{foreach([^\{\}]*)\}/', '<?php foreach\\1{ ?>', $neirong);
		$neirong = preg_replace(array('/\{\/while\}/','/\{\/foreach\}/','/\{\/if\}/','/\{\/for\}/'), '<?php } ?>', $neirong);
		$neirong = preg_replace('/\{temp\((.*)\)\}/', '<?php admintemp::_temp(\\1,$post); ?>',$neirong);
		$con = C_base::M('admin.base')->con_s();//读取网站设置
		$neirong = preg_replace('/\{photo\((.*)\)\}/', $con['url'].'/material/photo.php?id=\\1', $neirong);
		$neirong = preg_replace('/\{file\((.*)\)\}/', $con['url'].'/material/file.php?id=\\1', $neirong);
		@file_put_contents($cach,$neirong);   //将解析后的内容写入缓存文件
	}
	
	
}